package com.hoshiicloud.goods.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.UploadFileResponse;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.goods.entity.goods.Gallery;
import com.hoshiicloud.goods.entity.goods.GoodsCategory;
import com.hoshiicloud.goods.entity.goods.GoodsGallery;
import com.hoshiicloud.goods.entity.sku.BaseSku;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.entity.sku.ProductManage;
import com.hoshiicloud.goods.entity.sku.VendorGoodsSku;
import com.hoshiicloud.goods.entity.spu.*;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.feign.StoreFeignService;
import com.hoshiicloud.goods.feign.UpLoadFileService;
import com.hoshiicloud.goods.mapper.goods.GoodsReleaseMapper;
import com.hoshiicloud.goods.param.goods.GoodsReleaseSkuParam;
import com.hoshiicloud.goods.param.goods.GoodsReleaseSpuParam;
import com.hoshiicloud.goods.service.*;
import com.hoshiicloud.goods.vo.GoodsPropertiesVo;
import com.hoshiicloud.user.entity.store.PlatStore;
import com.hoshiicloud.user.param.PlatStoreQueryParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * @author linjx on 2019/7/31
 */
@Slf4j
@Service
public class GoodsReleaseServiceImpl implements GoodsReleaseService {

    @Autowired
    private GoodsPropertiesService goodsPropertiesService;
    @Autowired
    private PublicPropertiesService publicPropertiesService;
    @Autowired
    private GoodsBrandService goodsBrandService;
    @Autowired
    private BaseSpuService baseSpuService;
    @Autowired
    private ExtSpuService extSpuService;
    @Autowired
    private BaseSkuService baseSkuService;
    @Autowired
    private ExtSkuService extSkuService;
    @Autowired
    private VendorGoodsSkuService vendorGoodsSkuService;
    @Autowired
    private ProductManageService productManageService;
    @Autowired
    private GoodsReleaseMapper goodsReleaseMapper;
    @Autowired
    private GoodsCategoryService goodsCategoryService;
    @Autowired
    private UpLoadFileService upLoadFileService;
    @Autowired
    private SpuSalesCategoryService spuSalesCategoryService;
    @Autowired
    private GalleryService galleryService;
    @Autowired
    private GoodsGalleryService goodsGalleryService;
    @Autowired
    private ExtSpuTagsService extSpuTagsService;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private BaseGoodsGalleryService baseGoodsGalleryService;
    @Autowired
    private StoreFeignService storeFeignService;


    /**
     * 文件上传
     */
    @Override
    public Response uploadFile(MultipartFile file) {
        String bucketName = "obs-7d37";
        String objectKey = file.getOriginalFilename();
        String fileName = file.getOriginalFilename();
        String folder = "goods";
        Boolean privateOwned = false;
        Response<UploadFileResponse> response = upLoadFileService.fileUpload(bucketName, objectKey, fileName, folder, privateOwned, file);
        log.info("goods域文件上传返回数据:{}", response);
        return response;
    }

    /**
     * 查询与商品发布相关的信息
     */
    @Override
    public Map<String, Object> queryMessage(Long categoryId, Map<String, Object> myMap) {

        Map<String, Object> map = new HashMap<>();
        Long companyId = Long.valueOf(myMap.get("companyId").toString());
        // 类目属性
        List<GoodsPropertiesVo> properties = goodsPropertiesService.getPropertiesVoList(categoryId, companyId);
        // 包装单位
        String propertyName = "包装单位";
        String key = "DropdownBoxQuery{companyId=" + companyId + ",propertyName=" + propertyName + "}";
        List<String> packagings = publicPropertiesService.queryDropdownBox(companyId, propertyName, key);
        // 销售单位
        String propertyNameSales = "销售单位";
        String key1 = "DropdownBoxQuery{companyId=" + companyId + ",propertyName=" + propertyNameSales + "}";
        List<String> sales = publicPropertiesService.queryDropdownBox(companyId, propertyNameSales, key1);
        // 品牌
        List<Map<String, Object>> brand = goodsBrandService.getGoodsBrandsByCateId(categoryId);
        // 商品标签
        List<String> extSpuTagsSelect = Arrays.asList("新鲜", "有机", "无残留");
        // 根据店铺Id, 查询店铺类型 国内还是跨境 1.B2C(国内) 2.B2C（国外）3.C2C 4.O2O' (1,3,4 国内)
        PlatStore platStore = storeFeignService.queryById(Long.parseLong(myMap.get("storeId") + "")).getData();

        Integer type = platStore.getType();
        Integer purchaseType = type == null? 1: type == 2?2:1;

        map.put("purchaseType", purchaseType);
        map.put("properties", properties);
        map.put("sales", sales);
        map.put("packagings", packagings);
        map.put("brand", brand);
        map.put("extSpuTagsSelect", extSpuTagsSelect);
        return map;
    }

    /**
     * 发布商品
     */
    @Transactional
    @Override
    public Boolean saveGoods(GoodsReleaseSpuParam param) {


        // 保存baseSpu
        BaseSpu baseSpu = this.saveBaseSpu(param);

        // 保存ExtSpu
        ExtSpu extSpu = this.saveExtSpu(param, baseSpu);

        // 保存营销类目
        this.saveSpuSalesCategory(param, extSpu);

        // 保存图片信息 BaseSpu + ExtSpu
        this.saveGallery(extSpu.getSpuId(), extSpu.getId(), param.getDefaultImage());

        // 保存商品标签
        this.saveExtSpuTags(extSpu.getSpuId(), extSpu.getId(), param.getExtSpuTags());

        //  保存sku
        List<GoodsReleaseSkuParam> skus = param.getListGoodsReleaseSku();
        this.saveSku(skus, baseSpu, extSpu, param);
        return true;
    }

    /**
     * 获得需要编辑的商品信息
     * */
    @Override
    public GoodsReleaseSpuParam getNeedEditGoods(Map<String, Object> map) {
        // 查询spu相关信息
        GoodsReleaseSpuParam needEditGoods = goodsReleaseMapper.getNeedEditGoods(map);
        if (needEditGoods == null) {
            throw new ServiceException("编辑失败，暂无相关商品条目信息");
        }
        // 处理返回给前端的数据
        this.dataMessage(needEditGoods);
        // 查询sku相关信息
        map.put("extSpuId", needEditGoods.getExtSpuId());
        List<GoodsReleaseSkuParam> skuList = goodsReleaseMapper.skuList(map);
        log.error("输出sku结果：{}", skuList.size());
        needEditGoods.setListGoodsReleaseSku(skuList);
        return needEditGoods;
    }

    /**
     * 商品编辑
     */
    @Override
    public Boolean editGoods(GoodsReleaseSpuParam param) {

        // 更新baseSpu
        BaseSpu baseSpu = this.setBaseSpuValue(param);
        baseSpu.setUpdatedBy(param.getUpdateBy());
        baseSpu.setId(param.getBaseSpuId());
        baseSpuService.updateById(baseSpu);

        // 更新extSpu
        ExtSpu extSpu = this.setExtSpuValue(param, baseSpu.getId(), 2);
        extSpu.setUpdatedBy(param.getUpdateBy());
        extSpu.setId(param.getExtSpuId());
        extSpuService.updateById(extSpu);

        // 更新营销类目, 1、设置更新的值 2、根据extSpuId查询其id  3、设置id并且更新
        SpuSalesCategory spuSalesCategory = this
                .setSpuSalesCategory(param.getCategoryId(), extSpu.getId(), extSpu.getSpuId());

        QueryWrapper<SpuSalesCategory> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SpuSalesCategory::getExtSpuId, param.getExtSpuId())
                .eq(SpuSalesCategory::getDeleted, 0);

        SpuSalesCategory spuSalesCat = spuSalesCategoryService.getOne(wrapper);
        spuSalesCategory.setId(spuSalesCat.getId());
        spuSalesCategoryService.updateById(spuSalesCategory);

        // 更新sku
        List<GoodsReleaseSkuParam> listSku = param.getListGoodsReleaseSku();
        this.updateSku(listSku, baseSpu, extSpu, param);

        // 更新图片信息
        Long extSpuId = param.getExtSpuId();
        this.updateGallery(baseSpu.getId(), extSpuId, param.getDefaultImage());

        // 更新商品标签
        this.updateExtSpuTags(baseSpu.getId(), extSpuId, param.getExtSpuTags());

        return true;
    }

    /**
     * 商品编辑， 更新总店+分店所有商品
     */
    @Override
    @Transactional
    public Boolean editAllGoods(GoodsReleaseSpuParam param) {

        // 获取总店及其旗下分店的Id
        List<Long> storeIds = this.listStoreIds(param.getStoreId());

        // 更新baseSpu
        BaseSpu baseSpu = this.editBaseSpuAll(param);

        // 更新ExtSpu 总店+分店
        List<Long> extSpuIds = this.editExtSpuAll(param, baseSpu, storeIds);

        // 更新其余信息: extSpuIds 需要更新的总店+ 分店的ext_spu信息
        this.updateConnectExtSpuDate(param, baseSpu, extSpuIds);

        // 更新sku相关信息
        List<GoodsReleaseSkuParam> listGoodsReleaseSku = param.getListGoodsReleaseSku();
        this.editAllSku(listGoodsReleaseSku, baseSpu, param, param.getExtSpuId(), storeIds);
        return true;
    }

   // ============================商品发布=======================================

    /** 保存baseSpu */
    private BaseSpu saveBaseSpu(GoodsReleaseSpuParam param) {
        String spuNo = this.creteSpuCode(StringUtils.join(param.getCategoryArr()), param.getPurchaseType(), LocalDateTime.now());
        // 保存BaseSpu
        BaseSpu baseSpu = this.setBaseSpuValue(param);

        String categoryIdStr = StringUtils.join(param.getCategoryArr(), "\',\'");
        String categoryContextQueryStr = "\'" + categoryIdStr + "\'";
        String categoryContext = goodsCategoryService.selectcategoryContext(categoryContextQueryStr);
        baseSpu.setStatus(1);
        baseSpu.setCreatedBy(param.getCreateBy());
        baseSpu.setCategoryContext(categoryContext);
        baseSpu.setSpuNo(spuNo);
        baseSpuService.save(baseSpu);
        return baseSpu;
    }

    /**  保存ExtSpu */
    private ExtSpu saveExtSpu(GoodsReleaseSpuParam param, BaseSpu baseSpu) {
        ExtSpu extSpu = this.setExtSpuValue(param, baseSpu.getId(), 1);
        extSpu.setStatus(param.getStatus());
        extSpu.setCreatedBy(param.getCreateBy());
        // 设置上下架时间
        if (baseSpu.getStatus() == 1) {
            extSpu.setUpTime(baseSpu.getCreatedTime());
        } else {
            extSpu.setDownTime(baseSpu.getCreatedTime());
        }
        // 设置权重为该店铺最大权重+1
        Long maxWeight = extSpuService.getMaxWeight(param.getStoreId());
        extSpu.setWeight(++maxWeight);

        extSpuService.save(extSpu);
        return extSpu;
    }

    /** 保存营销类目 */
    private void saveSpuSalesCategory(GoodsReleaseSpuParam param, ExtSpu extSpu) {
        SpuSalesCategory spuSalesCategory = this
                .setSpuSalesCategory(param.getCategoryId(), extSpu.getId(), extSpu.getSpuId());
        spuSalesCategory.setCreatedBy(param.getCreateBy());
        spuSalesCategory.setUpdatedBy(param.getCreateBy());
        spuSalesCategoryService.save(spuSalesCategory);
    }

    /**  图片保存 BaseSpu 和  ExtSpu */
    private void saveGallery(Long baseSpuId, Long spuId, String defaultImage) {
        String[] images = defaultImage.split(",");
        // 保存图片信息
        for (String image : images) {
            // 保存相册表
            Gallery gallery = new Gallery();
            gallery.setImgUrl(image);
            Gallery ga = galleryService.saveGallery(gallery);

            // 保存BaseSpu商品图片资源表信息
            BaseGoodsGallery baseGoodsGallery = new BaseGoodsGallery();
            baseGoodsGallery.setGoodsId(baseSpuId);
            baseGoodsGallery.setGalleryId(ga.getId());
            baseGoodsGallery.setWeight(0);
            baseGoodsGalleryService.save(baseGoodsGallery);

            // 保存ExtSpu商品图片资源表
            GoodsGallery goodsGallery = new GoodsGallery();
            goodsGallery.setExtSpuId(spuId);
            goodsGallery.setBaseSpuId(baseSpuId);
            goodsGallery.setGalleryId(ga.getId());
            goodsGalleryService.saveGoodsGallery(goodsGallery);
        }
    }

    /**  保存商品标签信息 */
    private void saveExtSpuTags(Long baseSpuId, Long extSpuId, List<String> extSpuTags) {
        for (String tagName : extSpuTags) {
            ExtSpuTags extspuTag = new ExtSpuTags();
            extspuTag.setSpuId(extSpuId);
            extspuTag.setBaseSpuId(baseSpuId);
            extspuTag.setTagName(tagName);
            extSpuTagsService.save(extspuTag);
        }
    }

    /** 保存sku相关信息 status: 上下架状态 Extsku用， baseSku默认使用上架状态  */
    private void saveSku(List<GoodsReleaseSkuParam> skus, BaseSpu baseSpu, ExtSpu extSpu, GoodsReleaseSpuParam param) {

        String skuCode = "";
        for (GoodsReleaseSkuParam skuParam : skus) {
            // 生成sku编码
            String skuNo = this.createSkuCode(baseSpu.getSpuNo(), skuCode);

            // 保存baseSku
            BaseSku baseSku = this.setBaseSkuValue(skuParam, baseSpu, param, 1);
            baseSku.setStatus(1);
            baseSku.setCreatedBy(baseSpu.getCreatedBy());
            baseSku.setSkuNo(skuNo);
            baseSkuService.save(baseSku);

            // 保存ExtSku
            ExtSku extSku = this.setExtSkuValue(skuParam, extSpu.getId(), baseSku.getId(), param, 1);
            extSku.setCreatedBy(baseSpu.getCreatedBy());
            if (param.getStatus() == 1) {
                extSku.setStatus(2);
            } else {
                extSku.setStatus(3);
            }
            extSkuService.save(extSku);

            // 保存供应商sku
            VendorGoodsSku vendorGoodsSku = this.setVendorGoodsSkuValue(skuParam, param, baseSpu, baseSku, 1);
            vendorGoodsSku.setCreatedBy(baseSpu.getCreatedBy());
            vendorGoodsSkuService.save(vendorGoodsSku);

            // 保存sku分配
            ProductManage productManage = this.setProductManageValue(skuParam, param, extSku, 1);
            productManage.setSkuNo(baseSku.getSkuNo());
            productManage.setBaseSkuId(baseSku.getId());
            productManage.setCreatedBy(baseSpu.getCreatedBy());
            productManageService.save(productManage);

            skuCode = skuNo;
        }
    }

    // ==================================商品编辑: 仅总店==========================================
    /** 更新sku相关信息 */
    private void updateSku(List<GoodsReleaseSkuParam> skus, BaseSpu baseSpu, ExtSpu extSpu,
                           GoodsReleaseSpuParam param) {
        for (GoodsReleaseSkuParam skuParam : skus) {

            // 更新baseSku
            BaseSku baseSku = this.editBaseSku(skuParam, baseSpu, param);

            // 更新extSku
            ExtSku extSku = this.editExtSku(skuParam, baseSpu, extSpu, baseSku, param);

            // 更新供应商商品
            this.editVendorGoodsSku(skuParam, param, baseSpu, baseSku);

            // 更新分配商品表
            this.editProductManage(skuParam, param, baseSpu, extSku);
        }
    }

    /** 编辑BaseSku */
    private BaseSku editBaseSku(GoodsReleaseSkuParam skuParam, BaseSpu baseSpu, GoodsReleaseSpuParam param) {
        BaseSku baseSku = this.setBaseSkuValue(skuParam, baseSpu, param, 2);
        baseSku.setId(skuParam.getBaseSkuId());
        baseSku.setUpdatedBy(baseSpu.getUpdatedBy());
        baseSkuService.updateById(baseSku);
        return baseSku;
    }

    /** 编辑ExtSku */
    private ExtSku editExtSku(GoodsReleaseSkuParam skuParam, BaseSpu baseSpu, ExtSpu extSpu, BaseSku baseSku, GoodsReleaseSpuParam param ) {

        UpdateWrapper<ExtSku> extSkuUpdateWrapper = new UpdateWrapper<>();
        extSkuUpdateWrapper.lambda().eq(ExtSku::getId,skuParam.getExtSkuId()).eq(ExtSku::getDeleted, 0);

        ExtSku extSku = this.setExtSkuValue(skuParam, extSpu.getId(), baseSku.getId(), param, 2);
        extSku.setUpdatedBy(baseSpu.getUpdatedBy());

        UpdateBatchParam<ExtSku> extSkuUpdate = new UpdateBatchParam<>();
        extSkuUpdate.setUpdateWrapper(extSkuUpdateWrapper);
        extSkuUpdate.setUpdateEntity(extSku);

        extSkuService.updateBatchByWrapper(extSkuUpdate);
        return extSku;
    }

    /** 编辑供应商商品 */
    private void editVendorGoodsSku(GoodsReleaseSkuParam skuParam, GoodsReleaseSpuParam param, BaseSpu baseSpu, BaseSku baseSku) {
        VendorGoodsSku vendorGoodsSku = this.setVendorGoodsSkuValue(skuParam, param, baseSpu, baseSku, 2);
        vendorGoodsSku.setId(skuParam.getVendorId());
        vendorGoodsSku.setUpdatedBy(baseSpu.getUpdatedBy());
        vendorGoodsSkuService.updateById(vendorGoodsSku);
    }

    /** 更新分配商品表 */
    private void editProductManage(GoodsReleaseSkuParam skuParam, GoodsReleaseSpuParam param, BaseSpu baseSpu, ExtSku extSku) {
        ProductManage productManage = this.setProductManageValue(skuParam, param, extSku, 2);
        productManage.setId(skuParam.getProductMangerId());
        productManage.setUpdatedBy(baseSpu.getUpdatedBy());
        productManageService.updateById(productManage);
    }

    /** 图片更新 */
    private void updateGallery(Long baseSpuId, Long spuId, String defaultImage) {


        // 删除BaseSpu商品图片资源表信息
        QueryWrapper<BaseGoodsGallery> baseGoodsGalleryWrapper = new QueryWrapper<>();
        baseGoodsGalleryWrapper.lambda().eq(BaseGoodsGallery::getGoodsId, baseSpuId).eq(BaseGoodsGallery::getDeleted, 0);
        baseGoodsGalleryService.remove(baseGoodsGalleryWrapper);

        // 删除ExtSpu商品图片资源表信息
        QueryWrapper<GoodsGallery> goodsGalleryWrapper = new QueryWrapper<>();
        goodsGalleryWrapper.lambda().eq(GoodsGallery::getExtSpuId, spuId).eq(GoodsGallery::getDeleted, 0);
        goodsGalleryService.remove(goodsGalleryWrapper);
        // 调用保存商品图片资源和相册的方法
        this.saveGallery(baseSpuId, spuId, defaultImage);
    }

    /** 更新商品标签信息 */
    private void updateExtSpuTags(Long baseSpuId, Long extSpuId, List<String> extSpuTags) {
        // 查询并且删除某个extSpu已经存在的Tag
        List<ExtSpuTags> tagList = extSpuTagsService.getBySpuId(extSpuId);
        tagList.stream().forEach(s -> extSpuTagsService.removeTagsById(s.getId()));

        // 调用添加方法，保存商品标签
        this.saveExtSpuTags(baseSpuId, extSpuId, extSpuTags);
    }

    // ==================================商品编辑:总店+分店==========================================
    /**  编辑BaseSpou信息 （总店+分店） */
    private BaseSpu editBaseSpuAll(GoodsReleaseSpuParam param) {
        BaseSpu baseSpu = this.setBaseSpuValue(param);
        baseSpu.setUpdatedBy(param.getUpdateBy());
        baseSpu.setId(param.getBaseSpuId());
        baseSpuService.updateById(baseSpu);

        // 设置base创建人等一些信息， 后面用到
        BaseSpu queryBaseSpu = baseSpuService.getById(param.getBaseSpuId());
        baseSpu.setCreatedBy(queryBaseSpu.getCreatedBy());
        baseSpu.setCreatedTime(queryBaseSpu.getCreatedTime());
        return baseSpu;
    }

    /**  编辑ExtSpou信息 （总店+分店） */
    private List<Long> editExtSpuAll(GoodsReleaseSpuParam param, BaseSpu baseSpu, List<Long> storeIds){
       // 设置需要更新的 ExtSpu的条件(通过 store_id进行过滤)
        QueryWrapper<ExtSpu> extSpuWrapper = new QueryWrapper<>();
        extSpuWrapper.lambda().eq(ExtSpu::getSpuId, param.getBaseSpuId()).in(ExtSpu::getStoreId, storeIds).eq(ExtSpu::getDeleted, 0);
        // 查询需要更新的ExtSpu的Id
        List<Long> extSpuIds = extSpuService.getBaseMapper().selectList(extSpuWrapper).stream().map(ExtSpu::getId)
                .collect(Collectors.toList());
        // 设置ExtSpu需要更新的信息
        ExtSpu extSpuUpdate = this.setExtSpuValue(param, baseSpu.getId(), 2);
        extSpuUpdate.setUpdatedBy(param.getUpdateBy());
        // 根据ExtSpu条件和需要更新的ExtSpu的信息进行更新
        UpdateBatchParam<ExtSpu> extSpuBatch = new UpdateBatchParam<>();
        extSpuBatch.setWrapper(extSpuWrapper);
        extSpuBatch.setUpdateEntity(extSpuUpdate);
        extSpuService.updateBatchByWrapper(extSpuBatch);
        // 返回需要更新的ExtSpu的Id
        return extSpuIds;
    }

    /**  更新于ExtSpu关联的的相关信息 */
    private void updateConnectExtSpuDate(GoodsReleaseSpuParam param, BaseSpu baseSpu, List<Long> extSpuIds) {

        // 更新标签信息
        this.editExtSpuTags(baseSpu, param, extSpuIds);

        // 更新 图片信息
        this.editGoodsGallers(baseSpu, param, extSpuIds);
    }

    /**  更新标签信息 （总店+ 分店）*/
    private void editExtSpuTags(BaseSpu baseSpu, GoodsReleaseSpuParam param, List<Long> extSpuIds) {

        Long baseSpuId = baseSpu.getId();
        // 更新标签信息
        QueryWrapper<ExtSpuTags> tagsWrapper = new QueryWrapper<>();
        tagsWrapper.lambda().in(ExtSpuTags::getSpuId, extSpuIds).eq(ExtSpuTags::getDeleted, 0);
        extSpuTagsService.remove(tagsWrapper);

        List<String> extSpuTags = param.getExtSpuTags();

        // 保存操作
        List<ExtSpuTags> tagList = new ArrayList();
        for (Long extSpuId : extSpuIds) {
            for (String tagName : extSpuTags) {
                ExtSpuTags spuTag = new ExtSpuTags();
                spuTag.setId(this.getId());
                spuTag.setTagName(tagName);
                spuTag.setBaseSpuId(baseSpuId);
                spuTag.setSpuId(extSpuId);
                spuTag.setCreatedTime(baseSpu.getCreatedTime());
                spuTag.setCreatedBy(baseSpu.getCreatedBy());
                spuTag.setUpdatedTime(LocalDateTime.now());
                spuTag.setUpdatedBy(param.getUpdateBy());
                tagList.add(spuTag);
            }
        }
        extSpuTagsService.saveTagsBatch(tagList);
    }

    /** 更新图片信息 （总店+分店）*/
    private void editGoodsGallers(BaseSpu baseSpu, GoodsReleaseSpuParam param, List<Long> extSpuIds) {

        Long baseSpuId = baseSpu.getId();

        // 删除该商品总店以及分店的所有关联相册的信息
        QueryWrapper<GoodsGallery> goodsGalleryWrapper = new QueryWrapper<>();
        goodsGalleryWrapper.lambda().in(GoodsGallery::getExtSpuId, extSpuIds).eq(GoodsGallery::getDeleted, 0);

        // 删除goods_Gallery
        goodsGalleryService.remove(goodsGalleryWrapper);

        // 获取图片信息
        String[] images = param.getDefaultImage().split(",");

        // 添加相册以及商品图片资源表信息
        List<Gallery> gallerys = new ArrayList<>();
        List<GoodsGallery> goodsGalleries = new ArrayList<>();

        for (String imageUrl : images) {
            // 生成 Gallery的Id
            Long galleryId = this.getId();
            // 设置保存信息
            Gallery gallery = new Gallery();
            gallery.setId(galleryId);
            gallery.setImgUrl(imageUrl);
            gallery.setCreateTime(LocalDateTime.now());
            gallery.setUpdateTime(LocalDateTime.now());
            gallery.setDeleted(0);
            gallerys.add(gallery);
        }

        // 批量保存相册表
        galleryService.saveGalleryBatch(gallerys);
        List<Long> galleryIds = gallerys.stream().map(Gallery::getId).collect(Collectors.toList());

        // 批量保存至BaseSpu相册关联表
        QueryWrapper<BaseGoodsGallery> baseGoodsGalleryWrapper = new QueryWrapper<>();
        baseGoodsGalleryWrapper.lambda().eq(BaseGoodsGallery::getGoodsId, baseSpuId).eq(BaseGoodsGallery::getDeleted, 0);
        baseGoodsGalleryService.remove(baseGoodsGalleryWrapper);

        for (Long galleryId : galleryIds) {
            BaseGoodsGallery baseGoodsGallery = new BaseGoodsGallery();
            baseGoodsGallery.setGoodsId(baseSpuId);
            baseGoodsGallery.setGalleryId(galleryId);
            baseGoodsGallery.setWeight(0);
            baseGoodsGallery.setUpdateTime(LocalDateTime.now());
            baseGoodsGalleryService.save(baseGoodsGallery);
        }

        // 批量保存到ExtSpu相册关联表
        for (Long extSpuId : extSpuIds) {
            for (Long galleryId : galleryIds) {

                // 生成 GoodsGallery的Id
                Long goodsGalleryId = this.getId();
                GoodsGallery goodsGallery = new GoodsGallery();
                goodsGallery.setId(goodsGalleryId);
                goodsGallery.setExtSpuId(extSpuId);
                goodsGallery.setGalleryId(galleryId);
                goodsGallery.setBaseSpuId(baseSpuId);
                goodsGallery.setCreatedTime(baseSpu.getCreatedTime());
                goodsGallery.setUpdatedTime(LocalDateTime.now());

                goodsGalleries.add(goodsGallery);
            }
        }
        goodsGalleryService.saveGoodsGalleryBatch(goodsGalleries);
    }

    /**  更新Sku 相关信息(总店+分店) */
    private void editAllSku(List<GoodsReleaseSkuParam> listGoodsReleaseSku, BaseSpu baseSpu, GoodsReleaseSpuParam param,
                            Long extSpuId, List<Long> storeIds) {

        listGoodsReleaseSku.stream().forEach(skuParam -> {

            // 更新BaseSku
            BaseSku baseSku = this.setBaseSkuValue(skuParam, baseSpu, param, 2);
            baseSku.setId(skuParam.getBaseSkuId());
            baseSku.setUpdatedBy(baseSpu.getUpdatedBy());
            baseSkuService.updateById(baseSku);


            // 更新ExtSku （总店+分店）
            // 查询需要更新的 ExtSku的Id
            QueryWrapper<ExtSku> extSkuWrapper = new QueryWrapper<>();
            extSkuWrapper.lambda().eq(ExtSku::getSkuId, skuParam.getBaseSkuId()).in(ExtSku::getStoreId, storeIds).eq(ExtSku::getDeleted, 0);
            List<Long> extSkuIds = extSkuService.getBaseMapper().selectList(extSkuWrapper).stream().map(ExtSku::getId).collect(Collectors.toList());

            UpdateWrapper<ExtSku> extSkuUpdateWrapper = new UpdateWrapper<>();
            extSkuUpdateWrapper.lambda().eq(ExtSku::getSkuId, skuParam.getBaseSkuId()).in(ExtSku::getStoreId, storeIds).eq(ExtSku::getDeleted, 0);

            ExtSku extSkuUpdate = this.setExtSkuValue(skuParam, extSpuId, baseSpu.getId(), param, 2);
            extSkuUpdate.setUpdatedBy(baseSpu.getUpdatedBy());

            UpdateBatchParam<ExtSku> extSkuBatch = new UpdateBatchParam<>();
            extSkuBatch.setUpdateWrapper(extSkuUpdateWrapper);
            extSkuBatch.setUpdateEntity(extSkuUpdate);
            extSkuService.updateBatchByWrapper(extSkuBatch);

            // 更新供应商商品
            VendorGoodsSku vendorGoodsSku = this.setVendorGoodsSkuValue(skuParam, param, baseSpu, baseSku, 2);
            vendorGoodsSku.setId(skuParam.getVendorId());
            vendorGoodsSku.setUpdatedBy(baseSpu.getUpdatedBy());
            vendorGoodsSkuService.updateById(vendorGoodsSku);

            // 更新ProductManager
            QueryWrapper<ProductManage> productManageWrapper = new QueryWrapper<>();
            productManageWrapper.lambda().in(ProductManage::getSkuId, extSkuIds)
                    .eq(ProductManage::getDeleted, 0);

            ProductManage productManageUpdate = this.setProductManageValue(skuParam, param, extSkuUpdate, 2);
            productManageUpdate.setUpdatedBy(baseSpu.getUpdatedBy());

            UpdateBatchParam<ProductManage> productManageBatch = new UpdateBatchParam<>();
            productManageBatch.setWrapper(productManageWrapper);
            productManageBatch.setUpdateEntity(productManageUpdate);
            productManageService.updateBatchByWrapper(productManageBatch);
        });

    }

    // ============================数据处理=======================================================
    /** 处理返回给前端的数据 */
    private void dataMessage(GoodsReleaseSpuParam needEditGoods) {
        // 处理 类目相关 放回类目 id 集合， 以及类目名称集合
        Long categoryId = needEditGoods.getCategoryId();
        GoodsCategory gc = goodsCategoryService.getById(categoryId);
        GoodsCategory parent = goodsCategoryService.getById(gc.getParentId());
        GoodsCategory one = goodsCategoryService.getById(parent.getParentId());
        Long[] categoryIds = new Long[]{parent.getParentId(), gc.getParentId(), categoryId};
        needEditGoods.setCategoryArr(categoryIds);
        needEditGoods.setCategoryIdStr(one.getName() + ">" + parent.getName() + ">" + gc.getName());

        // 图片出处理，分割图片传给前端
        List<String> images = Arrays.asList(needEditGoods.getDefaultImage().split(","));
        needEditGoods.setImageArr(images);
        // 视频处理
        needEditGoods.setCompleteSpuVideo(needEditGoods.getSpuVideo());
        // 横图处理
        needEditGoods.setCompleteHImage(needEditGoods.getHeImage());
        // 竖图处理
        needEditGoods.setCompleteVImage(needEditGoods.getVeImage());
        // 查询商品标签信息
        List<ExtSpuTags> extSpuTags = extSpuTagsService.getBySpuId(needEditGoods.getExtSpuId());
        List<String> tags = extSpuTags.stream().map(ExtSpuTags::getTagName).collect(Collectors.toList());
        needEditGoods.setExtSpuTags(tags);
    }

    /**  根据总店Id查询其所有子店Id, 返回总店+子店 的id集合  */
    private List<Long> listStoreIds(Long mainStoreId) {
        PlatStoreQueryParam param = new PlatStoreQueryParam();
        param.setPageNumber("1");
        param.setPageSize("10000");
        param.setParentId(mainStoreId);
        Response<Page<PlatStore>> listPlatStore = storeFeignService.getPlatStorePage(param);
        List<Long> listBranchStoreIds = listPlatStore.getData().getRecords().stream().map(PlatStore::getId).collect(Collectors.toList());
        listBranchStoreIds.add(mainStoreId);
        return listBranchStoreIds;
    }


    // ============================spu/sku编码生成以及ID生成=======================================

    /** spu编码生成 类目编码+商品类型+年月日（各取2位）+秒数（创建时间时分秒转换成秒数）+7位随机数  */
    private String creteSpuCode(String categoryCode, Integer purchaseType, LocalDateTime createTime) {
        StringBuffer spuCode = new StringBuffer(categoryCode.replace(",", ""));
        spuCode.append(purchaseType);
        spuCode.append(DateTimeFormatter.ofPattern("yyMMdd").format(createTime));
        spuCode.append(createTime.toLocalTime().toSecondOfDay());
        spuCode.append(ThreadLocalRandom.current().nextInt(1000000, 9999999));
        return spuCode.toString();
    }

    /** sku编码生成 SPU_CODE+序号（最大99，从01开始） */
    private String createSkuCode(String spuNo, String skuNo) {
        if (StringUtils.isBlank(skuNo)) {
            return spuNo + "01";
        } else {
            // 截取skuNo后两位
            String numStr = skuNo.substring(spuNo.length() - 2);
            // 自增1
            long num = Long.parseLong(numStr);
            String lastNo = String.format("%02d", ++num);
            // 截取原先skuNo 除了后两位的前面的位数
            String baseNo = spuNo.substring(0, spuNo.length() - 2);
            return baseNo + lastNo;
        }
    }

    /** 生成一个Id 并且返回 */
    private Long getId() {
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("主键ID生成失败"));
        }
        return Long.parseLong(id);
    }

    // ==================以下是一些字段的设置===================================

    /**
     * 设置BaseSpu需要保存的值 status: 上下架状态： baseSpu 始终处于上架状态
     */
    private BaseSpu setBaseSpuValue(GoodsReleaseSpuParam param) {

        BaseSpu baseSpu = new BaseSpu();
        // 公司Id
        baseSpu.setCompanyId(param.getCompanyId());
        // 平台Id
        baseSpu.setPlatformId(param.getPlatformId());
        // 店铺Id
        baseSpu.setStoreId(param.getStoreId());
        // 名称
        baseSpu.setTitle(param.getTitle());
        // 商品类目Id
        baseSpu.setCategoryId(param.getCategoryArr()[param.getCategoryArr().length - 1]);
        // 类目描述
        baseSpu.setCategoryDescribe(StringUtils.join(param.getCategoryArr(), ","));
        // 品牌
        baseSpu.setBrandId(param.getBrandId());
        // 商品类型
        baseSpu.setProductType(param.getProductType());
        // 采购类型
        baseSpu.setPurchaseType(param.getPurchaseType());
        // 属性
        baseSpu.setExtendProperty(param.getExtendProperty());
        // 默认图片
        baseSpu.setDefaultImage(param.getDefaultImage().split(",")[0]);
        // 1-共有 2-私有
        baseSpu.setPublished(1);
        // 规格
        Map<String, Object> map = new HashMap<>();
        map.put("spec_id", 3263976614391709706L);
        map.put("spec_name", "默认");
        map.put("spec_itemid", 3263976614391709716L);
        map.put("spec_itemname", "默认");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("spec1", map);

        baseSpu.setExtendSpec(JSONObject.toJSONString(map));
        return baseSpu;
    }

    /**
     * 设置ExtSpu需要保存的值 ExtSpu/Sku 上下架状态根据前端而定 type: 设置的类型 1 商品新增  2 商品编辑
     */
    private ExtSpu setExtSpuValue(GoodsReleaseSpuParam param, Long spuId, Integer type) {

        ExtSpu extSpu = new ExtSpu();

        //平台商铺等信息
        if (type == 1) {
            extSpu.setCompanyId(param.getCompanyId());
            extSpu.setPlatformId(param.getPlatformId());
            extSpu.setStoreId(param.getStoreId());
        }

        // spuId
        extSpu.setSpuId(spuId);
        // 商品标题
        extSpu.setTitle(param.getTitle());
        // 存储商品主图
        extSpu.setSpuImage(param.getDefaultImage().split(",")[0]);
        // 主图视频
        extSpu.setSpuVideo(param.getSpuVideo());
        // 图文描述
        extSpu.setSpuDescription(param.getSpuDescription());
        // 售后说明
        extSpu.setServiceDescription(param.getServiceDescription());
        // 购买须知
        extSpu.setNotice(param.getNotice());
        // 横图
        extSpu.setHImage(param.getHeImage());
        // 竖图
        extSpu.setVImage(param.getVeImage());
        // 权重
        extSpu.setWeight(param.getWeight());
        return extSpu;
    }

    /**
     * 设置营销类目需要保存的值
     *
     * @param salesCategoryId: 类目Id
     * @param extSpuId: 扩展spuId
     */
    private SpuSalesCategory setSpuSalesCategory(Long salesCategoryId, Long extSpuId, Long baseSpuId) {
        SpuSalesCategory spuSalesCategory = new SpuSalesCategory();
        spuSalesCategory.setSalesCategoryId(salesCategoryId);
        spuSalesCategory.setExtSpuId(extSpuId);
        spuSalesCategory.setBaseSpuId(baseSpuId);
        spuSalesCategory.setUpdatedTime(LocalDateTime.now());
        return spuSalesCategory;
    }

    /**
     * 设置BaseSku需要保存的值
     */
    private BaseSku setBaseSkuValue(GoodsReleaseSkuParam sku, BaseSpu baseSpu, GoodsReleaseSpuParam param,
            Integer type) {

        BaseSku baseSku = new BaseSku();

        if (type == 1) {
            //平台商铺等信息
            baseSku.setCompanyId(param.getCompanyId());
            baseSku.setPlatformId(param.getPlatformId());
            baseSku.setStoreId(param.getStoreId());
        }
        // spuid
        baseSku.setSpuId(baseSpu.getId());
        // 商品标题
        baseSku.setSkuTitle(param.getTitle());
        // 销售单位（*）
        baseSku.setSalesUnit(sku.getSalesUnit());
        // 条形码
        baseSku.setBarCode(sku.getBarCode());
        // 箱码
        baseSku.setPacketCode(sku.getPacketCode());
        // 规格
        baseSku.setExtendSpec(sku.getExtendSpec());
        // 是否负库存
        baseSku.setIsStored(0);
        // 是否允许分销 0-不允许分销 1-允许分销
        baseSku.setDistributorStatu(sku.getDistributorStatu());
        // 是否允许分店编辑售价 0-不允许 1-允许
        baseSku.setEditStatu(sku.getEditStatu());
        return baseSku;
    }

    /**
     * 设置ExtSku需要保存的值
     */
    private ExtSku setExtSkuValue(GoodsReleaseSkuParam skuParam, Long extSpuId, Long baseSkuId,
            GoodsReleaseSpuParam param, Integer type) {

        ExtSku extSku = new ExtSku();

        if (type == 1) {
            // 设置公司（租户）/平台/店铺，创建人 等相关信息
            extSku.setCompanyId(param.getCompanyId());
            extSku.setPlatformId(param.getPlatformId());
            extSku.setStoreId(param.getStoreId());
            // ExtSku中的 spuId 对应的是 ExtSpu中的Id
            extSku.setSpuId(extSpuId);
            extSku.setSkuId(baseSkuId);
        }

        extSku.setSkuTitle(param.getTitle());

        // sku 图片
        extSku.setSkuImage(param.getDefaultImage().split(",")[0]);
        // 售价
        extSku.setSalePrice(skuParam.getSalePrice());
        // 市场价
        extSku.setMarketPrice(skuParam.getMarketPrice());
        // 成本价
        extSku.setCostPrice(skuParam.getCostPrice());
        // 是否库库存足够才能下单  1 是 0 否
        extSku.setStoreEnough(1);
        // 规格
        Map<String, Object> map = new HashMap<>();
        map.put("spec_id", 3263976614391709706L);
        map.put("spec_name", "默认");
        map.put("spec_itemid", 3263976614391709716L);
        map.put("spec_itemname", "默认");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("spec1", map);
        extSku.setExtendSpec(JSONObject.toJSONString(map2));
        // 收货间隔时间
        extSku.setReceiptInterval(skuParam.getReceiptInterval());
        // 提货时间
        extSku.setReceiptDate(skuParam.getReceiptDate());
        return extSku;
    }

    /**
     * 设置供应商sku需要保存的值
     */
    private VendorGoodsSku setVendorGoodsSkuValue(GoodsReleaseSkuParam skuParam, GoodsReleaseSpuParam param,
            BaseSpu baseSpu, BaseSku baseSku, Integer type) {

        VendorGoodsSku vendorSku = new VendorGoodsSku();

        if (type == 1) {
            // 设置公司（租户）/平台/店铺，创建人 等相关信息
            vendorSku.setCompanyId(param.getCompanyId());
            vendorSku.setPlatformId(param.getPlatformId());
            vendorSku.setStoreId(param.getStoreId());
            // skuId
            vendorSku.setSkuId(baseSku.getId());
            // spuId
            vendorSku.setSpuId(baseSpu.getId());
        }

        // 条形码
        vendorSku.setBarCode(skuParam.getBarCode());
        // 箱码
        vendorSku.setPacketCode(skuParam.getPacketCode());
        // 包装单位
        vendorSku.setPacketUnit(skuParam.getPacketUnit());
        // 内件数
        vendorSku.setInnerBoxs(skuParam.getInnerBoxs());
        // 商品重量
        vendorSku.setWeight(skuParam.getWeight());
        // 供价（不含税）
        vendorSku.setUnitPrice(skuParam.getUnitprice());
        // 供价（含税）
        vendorSku.setTaxUnitprice(skuParam.getTaxUnitprice());
        // 增值税率
        vendorSku.setTaxRate(skuParam.getTaxRate());
        // 采购类型
        vendorSku.setVendorPoType(skuParam.getVendorPoType());

        return vendorSku;
    }

    /**
     * 设置SKU分配需要保存的值
     */
    private ProductManage setProductManageValue(GoodsReleaseSkuParam skuParam, GoodsReleaseSpuParam param,
            ExtSku extSku, Integer type) {

        ProductManage product = new ProductManage();

        if (type == 1) {
            // 设置公司（租户）/平台/店铺，创建人 等相关信息
            product.setCompanyId(param.getCompanyId());
            product.setPlatformId(param.getPlatformId());
            product.setStoreId(param.getStoreId());
            // 之前如果是做更新操作， 因为 extSku的id为null 或 空数据库是不更新的，所以设置也无妨
            product.setSkuId(extSku.getId());
        }
        product.setSkuName(extSku.getSkuTitle());
        product.setQuantity(new BigDecimal(skuParam.getQuantity()));
        product.setUnit(skuParam.getPacketUnit());
        product.setSource(0);
        product.setFreezes(BigDecimal.ZERO);
        return product;
    }
}
